package com.linian.pushforcampus.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.linian.pushforcampus.domain.*;
import com.linian.pushforcampus.service.*;
import com.linian.pushforcampus.util.HttpUtil;
import com.linian.pushforcampus.util.SymmetricEncryptionUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static com.linian.pushforcampus.enums.EducationType.getByCode;
import static com.linian.pushforcampus.enums.EducationType.getByDescription;
import static com.linian.pushforcampus.util.HttpUtil.sendGetHearderRequest;

/**
 * packageName com.linian.pushforcampus.service.Impl
 *
 * @author Lennon
 * @className PushingServiceImpl
 * @date 2023/11/10
 * @description TODO
 */
@Service
@Slf4j
public class PushingServiceImpl implements PushingService {
    @Autowired
    private PushConfigure pushConfigure;
    @Autowired
    private UserService userService;
    @Autowired
    private VipService vipService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private ExternalService externalService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private StudentService studentService;

    @Autowired
    private CampusActivityService campusActivityService;
    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;


    @Override
    public String wxpushingmsg(List<CampusActivity> campusActivities) {

        //获取需要推送的用户，并与此同时更新了数据库对应用户的相关信息
        List<User> nowUserByWechat = userService.getNowUserByWechat();
        //拉取微信api关注用户，然后查询数据库中用户信息，如果

        for (User user : nowUserByWechat) {
            //在数据库查找存活用户，如果datastate为0，说明用户还没有授权，则推送提醒授权模板

            //不用担心肯定能搜到，因为在数据库中已经插入了用户信息
            User surviveUser = userService.getAllUsersByUser(user).get(0);
            if (surviveUser.getDataState().intValue() == 1) {

                for (CampusActivity campusActivity : campusActivities) {

                    try {
                        //查询vip
                        Vip vipByUserIdFromUserID = vipService.getVipByUserIdFromUserID(surviveUser.getUserId());
                        //判断是否是vip且状态有效
                        if (vipByUserIdFromUserID != null && !vipByUserIdFromUserID.getIsVip().equals("-1")) {
                            //说明是vip直接推送vip的摸板消息

                            String memo = surviveUser.getMemo();
                            if (memo == null || !memo.equals("close")) {
                                wxMpService.getTemplateMsgService().sendTemplateMsg(templateVip(vipByUserIdFromUserID, campusActivity));
                            }
                            //推送后直接下一个用户走起
                            continue;
                        }
                        //说明不是vip,推送普通用户摸板
                        wxMpService.getTemplateMsgService().sendTemplateMsg(templateUser(surviveUser, campusActivity));

                    } catch (Exception e) {
                        log.error("推送失败：" + e.getMessage());

                    }
                }
            } else {
                // 推送授权信息,此方法是客服方法，没有办法做到全部推送，所以还是需要通过消息模板
                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(authorizationTemplate(surviveUser));
                } catch (Exception e) {
                    log.error("推送失败：" + e.getMessage());

                }
            }


        }

        return "全部推送成功";
    }

    @Override
    public String wxpushingmsgForAutoGrab(CampusActivity campusActivity, Vip vip) {
        //1，配置

        try {

            wxMpService.getTemplateMsgService().sendTemplateMsg(autoTemplate(campusActivity, vip));
        } catch (Exception e) {
            log.error("推送失败：" + e.getMessage());

        }
        return "全部推送成功";
    }

    @Override
    public WeChatSendResp wxSendCustomMessage(String touser, String msgtype, String content, String token) {
        JSONObject json = new JSONObject();
        json.put("touser", touser);
        json.put("msgtype", msgtype);
        JSONObject text = new JSONObject();
        text.put("content", content);
        json.put("text", text);
        String jsonString = json.toJSONString();
        try {
            String out = HttpUtil.sendPostRequest(pushConfigure.getWECHATSENDCUSTOMMESSAGE() + "?access_token=" + token, jsonString);
            return JSONObject.parseObject(out, WeChatSendResp.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public String receiveMessage(Map<String, String> param) {
        String content = "";
        String msgType = param.get("MsgType");
        //判断什么类型消息
        switch (msgType) {
            case "text":    //普通文本类型,输入关键字java、mysql等
                content = this.search(param);
                break;
            case "event":   //关注、取消关注、点击关于我们
                String event = param.get("Event");
                String eventKey = param.get("EventKey");
                //关注
                if ("subscribe".equals(event)) {  //关注
                    content = this.subscribe(param);
                } else if ("unsubscribe".equals(event)) { //取消关注
                    content = this.unsubscribe(param);
                } else if ("CLICK".equals(event) && "AboutUs".equals(eventKey)) {  //关于我们
                    content = this.aboutUs(param);
                } else if ("CLICK".equals(event) && "Authorization".equals(eventKey)) {  //用户授权
                    content = this.authorization(param);
                } else if ("CLICK".equals(event) && "CampusToday".equals(eventKey)) { //今日校园登录接口
                    content = this.campusToday(param);
                } else {
                    content = "success";
                }
                break;
            default:    //其他情况
                content = "success";
        }
        return content;

    }

    private String campusToday(Map<String, String> param) {
        return textUrlAndPic(param, "今日校园登录", "登录完成后，课程推送后点击模板即可跳转到详情页！", pushConfigure.getCAMPUSFORSANDA(), null);

    }

    private String campusQRCode(Map<String, String> param) {
        return textUrlAndPic(param, param.get("title"), "获取当前课程签到码", param.get("url"), param.get("picurl"));
    }


    //关于我们
    private String aboutUs(Map<String, String> param) {
        return this.text(param, "pushingTeam独家二课推送，不用于利益，只用于学习 By-------------Lennon&Qili").toString();
    }


    //用户授权
    private String authorization(Map<String, String> param) {
        return textUrlAndPic(param, "欢迎关注pushingTeam", "点击授权,不授权不推送哦！！！", pushConfigure.getWECHATAUTHURL() + "/wechat/authorize", null);

    }

    //取消关注
    private String unsubscribe(Map<String, String> param) {

        //用户取关，更新用户状态为0
        User user = new User();
        String userId = param.get("FromUserName");

        user.setUserId(userId);
        User userToDateBase = userService.getAllUsersByUser(user).get(0);
        userToDateBase.setDataState(0);
        userService.updateUser(userToDateBase);
        //用户取关，更新vip表状态

        Vip vipByUserIdFromUserID = vipService.getVipByUserIdFromUserID(userId);
        if (vipByUserIdFromUserID != null) {
            vipByUserIdFromUserID.setIsVip("-1");
            vipService.updateVip(vipByUserIdFromUserID);
        }

        return "success";
    }

    //关注逻辑事件
    private String subscribe(Map<String, String> param) {
        //当用户点击关注后，直接插入数据库，但是授权状态为0，需要用户授权后才能推送
        String openId = param.get("FromUserName");
        User user = new User();
        user.setUserId(openId);
        List<User> allUsersByUser = userService.getAllUsersByUser(user);
        if (allUsersByUser.size() == 0) {
            //没有授权，状态为0
            //设置当前时间
            LocalDateTime now = LocalDateTime.now();
            user.setDataState(0);
            user.setIsVip(0);
            user.setUpdateTime(now);
            user.setCreateTime(now);
            userService.insertUser(user);
        }
        //授权信息模板
        return textUrlAndPic(param, "欢迎关注pushingTeam", "点击授权,不授权不推送哦！！！,还有哦，授权后记得点击CampusToday，这样就可以跳转直接抢课了哦！！！", pushConfigure.getWECHATAUTHURL() + "/wechat/authorize", null);


    }


    /**
     * 处理关键字搜索事件
     * 图文消息个数；当用户发送文本、图片、语音、视频、图文、地理位置这六种消息时，开发者只能回复1条图文消息；其余场景最多可回复8条图文消息
     *
     * @param param
     * @return
     */
    private String search(Map<String, String> param) {


        //获取用户发送的内容
        String content = param.get("Content");
        //根据用户发送的内容，查询数据库，返回对应的图文消息
//        campusActivityService.querryActivityByName(content);


        String paramBroadcast = getBroadcastContent(param, content);
        if (paramBroadcast != null) return paramBroadcast;
        String paramVIP = getVipContent(param, content);
        if (paramVIP != null) return paramVIP;
        String paramUserToVip = getUserToVipContent(param, content);
        if (paramUserToVip != null) return paramUserToVip;

        return this.text(param, "暂时没有搜索功能，不要调皮哦！！！").toString();

    }

    private String getBroadcastContent(Map<String, String> param, String contents) {

        String fromusername = param.get("FromUserName");
        //查询是不是管理员发送的消息
        Vip vipByUserIdFromUserID = vipService.getVipByUserIdFromUserID(fromusername);
        //查询数据库此用户的权限
        if ((vipByUserIdFromUserID == null) || !(vipByUserIdFromUserID.getIsVip().equals("8"))) {
            return null;
        }
        String regex = "@([0-9]+|all|vip)to.+";
        if (contents.matches(regex)) {
            Thread thread = new Thread() {
                String content = contents;

                @Override
                public void run() {
                    //如果是管理员，就推送给所有用户
                    //判断是否有@符号，
                    //解析是全体成员还是独立用户
                    //去除输入的空格
                    content = content.replace(" ", "");
                    // 截取 "@" 和 "to" 之间的文字作为一个新的字符串
                    int indexOfAt = content.indexOf("@");
                    int indexOfTo = content.indexOf("to");
                    String atText = content.substring(indexOfAt + 1, indexOfTo);

                    // 截取 "to" 后面的文字部分
                    String toText = content.substring(indexOfTo + 2);
                    List<User> allUsersWhoState1 = userService.getUserByIdWhoState1();
                    if (atText.equals("all")) {
                        for (User user : allUsersWhoState1) {
                            try {
                                wxMpService.getTemplateMsgService().sendTemplateMsg(DeveloperTemplateMessage(user, vipByUserIdFromUserID.getUserName(), "请看下面的信息"));
                                wxSendCustomMessage(user.getUserId(), "text", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                            } catch (WxErrorException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        wxSendCustomMessage(fromusername, "全部关注人员公告推送成功！", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());

                    } else if (atText.equals("vip")) {
                        List<Vip> vipSurvive = vipService.getVipSurvive();
                        if (vipSurvive.size() > 0) {
                            for (Vip vip : vipSurvive) {
                                try {
                                    User user = new User();
                                    user.setUserName(vip.getUserName());
                                    user.setUserId(vip.getUserId());
                                    wxMpService.getTemplateMsgService().sendTemplateMsg(DeveloperTemplateMessage(user, vipByUserIdFromUserID.getUserName(), "请看下面的信息"));
                                    wxSendCustomMessage(vip.getUserId(), "text", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                                } catch (WxErrorException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            wxSendCustomMessage(fromusername, "全部VIP关注人员公告推送成功！", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                        } else {
                            wxSendCustomMessage(fromusername, "当前没有VIP关注人员！", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());

                        }
                    } else {
                        //通过id查询用户
                        User userById = userService.getUserById(Integer.valueOf(atText));
                        if (userById != null) {
                            try {
                                wxMpService.getTemplateMsgService().sendTemplateMsg(DeveloperTemplateMessage(userById, vipByUserIdFromUserID.getUserName(), "请看下面的信息"));
                                wxSendCustomMessage(userById.getUserId(), "text", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                            } catch (WxErrorException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            wxSendCustomMessage(fromusername, "你输入的用户ID不存在！", toText, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());

                        }

                    }

                }
            };


            thread.start();
        } else return null;

        return this.text(param, "推送成功").toString();

    }

    private String getUserToVipContent(Map<String, String> param, String content) {
        if (param.containsKey("FromUserName")) {
            String fromUserName = param.getOrDefault("FromUserName", "");
            Vip vipByUserIdFromUserID = vipService.getVipByUserIdFromUserID(fromUserName);
            if (vipByUserIdFromUserID == null) {
                User userByCode = userService.getUserByCode(fromUserName);
                if (content.equals("我要激活账号")) {
                    cacheService.initCache(1800);
                    cacheService.createCache(fromUserName, "stepOne");
                    return this.text(param, "请在30分钟完成激活操作\n" + "请输入激活码(づ￣3￣)づ╭❤～").toString();
                }
                try {
                    if (cacheService.getCache(fromUserName) != null) {
                        switch (cacheService.getCache(fromUserName)) {
                            case "stepOne":
                                WechatAccessToken allWechatAccessToken = wechatAccessTokenService.getAllWechatAccessToken();
                                String accessToken = allWechatAccessToken.getAccessToken();
                                if (content.equals(accessToken)) {
                                    cacheService.updateCache(fromUserName, "stepTwo");
                                    return this.text(param, "请输入您学校官网学号").toString();
                                } else {
                                    return this.text(param, "激活码错误，请重新输入").toString();
                                }
                            case "stepTwo":
                                cacheService.createCache(userByCode.getUserName() + "-userName", content);
                                cacheService.updateCache(fromUserName, "stepThree");
                                return this.text(param, "请输入您学校官网密码").toString();
                            case "stepThree":
                                cacheService.createCache(userByCode.getUserName() + "-pwd", content);
                                cacheService.updateCache(fromUserName, "stepFour");
                                //调用线程进行服务器访问
                                Thread thread = getThread(userByCode, fromUserName);
                                thread.start();
                                return this.text(param, "请稍等...正在读取您的信息...期间暂时不要输入消息").toString();
                            case "stepFour":
                                return this.text(param, "请稍等...正在读取您的信息...期间暂时不要输入消息").toString();
                        }

                    }
                } catch (Exception e) {
                    return null;
                }
            }
        }
        return null;
    }

    private Thread getThread(User userByCode, String fromUserName) {
        //进行校验操作 创建线程调用HttpUtil.getHttpJsonByUrl
        Thread thread = new Thread() {
            String userName = cacheService.getCache(userByCode.getUserName() + "-userName");
            String pwd = cacheService.getCache(userByCode.getUserName() + "-pwd");

            @Override
            public void run() {
                String tokenAndStudentId = externalService.getTokenAndStudentId(userName, pwd);
                String userId = null;
                String nickName = null;
                if (!tokenAndStudentId.isEmpty()) {
                    try {
                        String json = sendGetHearderRequest(pushConfigure.getCAMPUSAPYGETMYUSERINFOURL(), tokenAndStudentId);
                        JSONObject jsonObject = JSONObject.parseObject(json);
                        if (jsonObject.getString("code").equals("200")) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            userId = data.getString("userId");
                            nickName = data.getString("nickName");

                        } else {
                            wxSendCustomMessage(fromUserName, "text", "请联系管理员!!!", wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    getUserToVip(fromUserName, tokenAndStudentId, userId, nickName);
                    String finalNickName = nickName;
                    studentService.createStudent(new Student() {{
                        setUserId(fromUserName);
                        setStudentId(userName);
                        setStudentName(finalNickName);
                        setPassword(pwd);
                    }});
                    wxSendCustomMessage(fromUserName, "text", finalNickName + " 欢迎您加入VIP", wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                    cacheService.closeCache();
                } else {
                    cacheService.updateCache(fromUserName, "stepTwo");
                    wxSendCustomMessage(fromUserName, "text", "学号或密码错误,请重新输入学号!!", wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                }
            }
        };
        return thread;
    }

    private User getUserToVip(String fromUserName, String xtoken, String studentId, String userName) {
        User userByCode = userService.getUserByCode(fromUserName);
        Vip vip = new Vip();
        vip.setUserId(userByCode.getUserId());
        vip.setXIdToken(xtoken);
        vip.setStudentId(studentId);
        vip.setUserRealName(userName);
        vip.setUserName(userByCode.getUserName());
        vip.setDataState("0");
        vip.setIsVip("2");
        vipService.insertVip(vip);
        userByCode.setIsVip(1);
        userService.updateUser(userByCode);
        return userByCode;
    }

    private String getVipContent(Map<String, String> param, String content) {
        if (param.containsKey("FromUserName")) {
            String fromUserName = param.getOrDefault("FromUserName", "");
            Vip vipByUserIdFromUserID = vipService.getVipByUserIdFromUserID(fromUserName);
            if (vipByUserIdFromUserID != null) {
                String userName = vipByUserIdFromUserID.getUserName();
                String dataState = vipByUserIdFromUserID.getDataState();
                String msgOut = "";
                if (vipByUserIdFromUserID.getIsVip().equals("8") || vipByUserIdFromUserID.getIsVip().equals("2")) {
                    msgOut = "当前VIP用户只开放了:";
                }
                if (vipByUserIdFromUserID.getIsVip().equals("8")) {
                    msgOut += "\n'获取所有用户'\n'获取所有VIP用户'\n'获取当前激活码'\n'关闭用户X(数字)'\n'开启用户X(数字)'";
                    switch (content) {
                        case "获取所有VIP用户":
                            StringBuilder stringBuilder = new StringBuilder();
                            List<Vip> allVips = vipService.getAllVips();
                            for (Vip vip : allVips) {
                                stringBuilder.append(vip.getId()).append("--").append(vip.getUserName()).append("--").append((vip.getIsVip().equals("2") ? "VIP用户" : (vip.getIsVip().equals("8") ? "管理员" : (vip.getIsVip().equals("-1") ? "已过期用户" : "未知状态")))).append("--").append(vip.getDataState().equals("0") ? "已关闭自动抢课" : (vip.getDataState().equals("1") ? "已开启自动抢课" : "未知状态")).append("\n");
                            }
                            String result = stringBuilder.toString();
                            return this.text(param, result).toString();
                        case "获取所有用户":
                            StringBuilder stringBuilderUser = new StringBuilder();
                            List<User> allUsers = userService.getAllUsers();
                            for (User user : allUsers) {
                                stringBuilderUser.append(user.getId()).append("--").append(user.getUserName()).append("--").append(user.getIsVip().equals(1) ? "VIP用户" : (user.getIsVip().equals(0) ? "普通用户" : "未知状态")).append("--").append(user.getDataState().equals(1) ? "已授权" : (user.getDataState().equals(0) ? "未授权" : "未知状态")).append("\n");
                            }
                            String resultUser = stringBuilderUser.toString();
                            return this.text(param, resultUser).toString();
                        case "获取当前激活码":
                            WechatAccessToken allWechatAccessToken = wechatAccessTokenService.getAllWechatAccessToken();
                            return this.text(param, (allWechatAccessToken.getAccessToken())).toString();
                        default:
                            if (content.contains("用户")) {
                                if (content.contains("关闭用户")) {
                                    String Id = content.substring(4);
                                    Vip vipByUserIdFromUserIDUserIn = vipService.getVipById(Integer.parseInt(Id));
                                    if (vipByUserIdFromUserIDUserIn != null) {
                                        vipByUserIdFromUserIDUserIn.setIsVip("-1");
                                        vipByUserIdFromUserIDUserIn.setDataState("0");
                                        vipService.updateVip(vipByUserIdFromUserIDUserIn);
                                        return this.text(param, vipByUserIdFromUserIDUserIn.getUserName() + " 关闭用户成功！！！").toString();
                                    }
                                } else if (content.contains("开启用户")) {
                                    String Id = content.substring(4);
                                    Vip vipByUserIdFromUserIDUserIn = vipService.getVipById(Integer.parseInt(Id));
                                    if (vipByUserIdFromUserIDUserIn != null) {
                                        vipByUserIdFromUserIDUserIn.setIsVip("2");
                                        vipService.updateVip(vipByUserIdFromUserIDUserIn);
                                        return this.text(param, vipByUserIdFromUserIDUserIn.getUserName() + " 开启用户成功！！！").toString();
                                    }
                                }
                            }
                    }
                } else if (vipByUserIdFromUserID.getIsVip().equals("-1") || vipByUserIdFromUserID.getIsVip().equals("1")) {
                    return this.text(param, "你的Vip状态权限过低，请联系管理员！！！").toString();
                }
                msgOut += "\n'开启自动抢课'\n'关闭自动抢课'\n'查看抢课状态'\n'我参与的课程'\n'签到码X(数字)'\n'切换推送模式'";
                switch (content) {
                    case "开启自动抢课":
                        vipByUserIdFromUserID.setDataState("1");
                        vipService.updateVip(vipByUserIdFromUserID);
                        return this.text(param, userName + " 开启抢课成功！！！").toString();
                    case "关闭自动抢课":
                        vipByUserIdFromUserID.setDataState("0");
                        vipService.updateVip(vipByUserIdFromUserID);
                        return this.text(param, userName + " 关闭抢课成功！！！").toString();
                    case "查看抢课状态":
                        String message = dataState.equals("0") ? (userName + " 当前是已关闭状态！！！") : (dataState.equals("1") ? (userName + " 当前是已开启状态！！！") : (userName + " 当前是未知状态，请联系管理员！！！"));
                        return this.text(param, message).toString();
                    case "切换推送模式":
                        String userId = vipByUserIdFromUserID.getUserId();
                        User userByCode = userService.getUserByCode(userId);
                        String memo = userByCode.getMemo();
                        if (memo != null && memo.equals("close")) {
                            userByCode.setMemo(null);
                            userService.updateUser(userByCode);
                            return this.text(param, "切换推送模式成功！当前已开启！").toString();
                        } else{
                            userByCode.setMemo("close");
                            userService.updateUser(userByCode);
                            return this.text(param, "切换推送模式成功！当前已关闭！").toString();
                        }
                    case "我参与的课程":
                        //调用线程进行服务器访问
                        Thread thread = new Thread(() -> {
                            Result result = getResult(vipByUserIdFromUserID);
                            if (!result.resultBString.isEmpty()) {
                                this.wxSendCustomMessage(fromUserName, "text", result.resultBString, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                            }
                            if (!result.resultCString.isEmpty()) {
                                this.wxSendCustomMessage(fromUserName, "text", result.resultCString, wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                            }
                            vipByUserIdFromUserID.setUserClass(JSON.toJSONString(result.mapList));
                            vipService.updateVip(vipByUserIdFromUserID);
                            this.wxSendCustomMessage(fromUserName, "text", userName + " 当前一共有" + result.mapList.size() + "课程!", wechatAccessTokenService.getAllWechatAccessToken().getAccessToken());
                        });
                        thread.start();
                        return this.text(param, "🤔请稍等...\n📚正在读取您的课程信息...\n😴期间暂时不要输入消息...").toString();
                    default:
                        if (content.contains("签到码")) {
                            content = content.replace(" ", "");
                            String Id = content.substring(3);
                            String userClass = vipByUserIdFromUserID.getUserClass();
                            if (userClass == null) {
                                return this.text(param, "你还未获取所有课程，请先 '我参与的课程' 获取！").toString();
                            }
                            if (userClass.equals("[]") || userClass.equals(""))
                                return this.text(param, "你还未获取所有课程，请先 '我参与的课程' 获取！").toString();
                            List<Map<String, String>> mapListPro = JSON.parseObject(userClass, new TypeReference<List<Map<String, String>>>() {
                            });
                            for (int i = 0; i < mapListPro.size(); i++) {
                                if ((mapListPro.get(i).get("id").equals(Id))) {
                                    String publishIdP = mapListPro.get(i).get("publishId").substring(mapListPro.get(i).get("publishId").length() - 8);
                                    String originCode = "{pi:" + publishIdP + ";ur:" + fromUserName.substring(fromUserName.length() - 6) + "}";
                                    String encrypt = null;
                                    String activityStartTime = mapListPro.get(i).get("activityStartTime");
                                    String activityEndTime = mapListPro.get(i).get("activityEndTime");
                                    try {
                                        encrypt = SymmetricEncryptionUtil.encrypt(originCode, pushConfigure.getSECRET_KEY());
                                        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        SimpleDateFormat outputFormat = new SimpleDateFormat("dd号HH:mm");
                                        Date startTime = inputFormat.parse(activityStartTime);
                                        Date endTime = inputFormat.parse(activityEndTime);
                                        activityStartTime = outputFormat.format(startTime);
                                        activityEndTime = outputFormat.format(endTime);
                                    } catch (Exception e) {
                                        throw new RuntimeException(e);
                                    }

                                    return textUrlAndPic(param, mapListPro.get(i).get("activityName"), "点击获取课程签到码!!\n请勿分享给他人!!!\n" + activityStartTime + "--" + activityEndTime, pushConfigure.getWECHATAUTHURL() + "/wechat/authorizeQrCode" + "?dataPro=" + encrypt, mapListPro.get(i).get("activityPicture"));
                                }
                            }
                            return this.text(param, "你输入的课程ID不存在！可以尝试'获取所有课程'中的ID").toString();
                        }
                        return this.text(param, msgOut).toString();
                }
            }
        }
        return null;
    }

    /**
     * 获取用户参与的课程
     *
     * @param vipByUserIdFromUserID
     * @return
     */
    private Result getResult(Vip vipByUserIdFromUserID) {
        List<String> activityByUserXToken;
        try {
            activityByUserXToken = campusActivityService.getActivityByUserXToken(vipByUserIdFromUserID.getXIdToken());
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        List<JSONObject> jsonList = new ArrayList<>();
        for (String s : activityByUserXToken) {
            JSONObject jsonObject = JSONObject.parseObject(s);
            JSONObject dataObject = jsonObject.getJSONObject("data");
            if (dataObject != null) {
                JSONArray recordsArray = dataObject.getJSONArray("records");
                if (recordsArray != null) {
                    for (int i = 0; i < recordsArray.size(); i++) {
                        JSONObject recordObject = recordsArray.getJSONObject(i);
                        String stageDetail = recordObject.getString("stageDetail");
                        String stage = recordObject.getString("stage");
                        String entryStatusName = recordObject.getString("entryStatusName");
                        String leaveStatusName = recordObject.getString("leaveStatusName");
                        String stageDetail2 = recordObject.getString("stageDetail2");
                        if (stageDetail.equals("已记录") || stageDetail.equals("未记录") || stageDetail.equals("未通过") || stage.equals("活动因特殊原因中止举办") || entryStatusName.equals("未通过") || leaveStatusName.equals("已请假") || stageDetail2.equals("已请假"))
                            continue;
                        jsonList.add(recordObject);
                    }
                }
            }
        }
        List<Map<String, String>> mapList = new ArrayList<>();
        for (int i = 0; i < jsonList.size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(i + 1));
            map.put("activityName", jsonList.get(i).getString("activityName"));
            map.put("publishId", jsonList.get(i).getString("publishId"));
            map.put("activityPicture", jsonList.get(i).getString("activityPicture"));
            map.put("activityStartTime", jsonList.get(i).getString("activityStartTime"));
            map.put("activityEndTime", jsonList.get(i).getString("activityEndTime"));
            mapList.add(map);
        }
        StringBuilder stringB = new StringBuilder();
        StringBuilder stringC = new StringBuilder();
        for (int i = 0; i < mapList.size(); i++) {
            Map<String, String> map = mapList.get(i);
            if (i < 25) {
                stringB.append(map.get("id")).append("--").append(map.get("activityName")).append("\n");
            } else {
                stringC.append(map.get("id")).append("--").append(map.get("activityName")).append("\n");
            }

        }
        Result result = new Result(mapList, stringB.toString(), stringC.toString());
        return result;
    }

    private static class Result {
        public final List<Map<String, String>> mapList;
        public final String resultBString;
        public final String resultCString;

        public Result(List<Map<String, String>> mapList, String resultBString, String resultCString) {
            this.mapList = mapList;
            this.resultBString = resultBString;
            this.resultCString = resultCString;
        }
    }

    /**
     * 回复文本
     *
     * @param param
     * @param content
     * @return
     */
    private StringBuffer text(Map<String, String> param, String content) {
        String fromusername = param.get("FromUserName");
        String tousername = param.get("ToUserName");
        //单位为秒，不是毫秒
        Long createTime = new Date().getTime() / 1000;
        StringBuffer text = new StringBuffer();
        text.append("<xml>");
        text.append("<ToUserName><![CDATA[" + fromusername + "]]></ToUserName>");
        text.append("<FromUserName><![CDATA[" + tousername + "]]></FromUserName>");
        text.append("<CreateTime><![CDATA[" + createTime + "]]></CreateTime>");
        text.append("<MsgType><![CDATA[text]]></MsgType>");
        text.append("<Content><![CDATA[" + content + "]]></Content>");
        text.append("</xml>");
        return text;
    }


    /**
     * 通用url回复消息，带照片的哦
     *
     * @return
     */
    private String textUrlAndPic(Map<String, String> param, String title, String description, String url, String picUrl) {
        if (picUrl == null)
            picUrl = "https://img1.baidu.com/it/u=525130350,248247963&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1700326800&t=6da0a8c078e62c795c055dc673688e24";
        //推送授权信息
        String fromusername = param.get("FromUserName");
        String tousername = param.get("ToUserName");
        //单位为秒，不是毫秒
        Long createTime = new Date().getTime() / 1000;
        StringBuffer text = new StringBuffer();
        StringBuffer articles = new StringBuffer();
        articles.append("<item>");
        articles.append("<Title><![CDATA[" + title + "]]></Title>");
        articles.append("<Description><![CDATA[" + description + "]]></Description>");
        articles.append("<Url><![CDATA[" + url + "]]></Url>");
        articles.append("<PicUrl><![CDATA[" + picUrl + "" + "]]></PicUrl>");
        articles.append("</item>");
        text.append("<xml>");
        text.append("<ToUserName><![CDATA[" + fromusername + "]]></ToUserName>");
        text.append("<FromUserName><![CDATA[" + tousername + "]]></FromUserName>");
        text.append("<CreateTime><![CDATA[" + createTime + "]]></CreateTime>");
        text.append("<MsgType><![CDATA[news]]></MsgType>");
        text.append("<ArticleCount><![CDATA[1]]></ArticleCount>");
        text.append("<Articles>");
        text.append(articles);
        text.append("</Articles>");
        text.append("</xml>");

        return text.toString();
    }

    /**
     * 普通用户的推送课程消息摸板
     *
     * @param user
     * @param campusActivity
     * @return
     */
    private WxMpTemplateMessage templateUser(User user, CampusActivity campusActivity) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().build();
        templateMessage.setUrl(pushConfigure.getCAMPUSACTIVITYPAGEURL().replace("PUBLISH_ID", campusActivity.getPublishId()));
        templateMessage.setToUser(user.getUserId());
        //推送课程id
        templateMessage.setTemplateId(pushConfigure.getTemplateId());
        templateMessage.addData(new WxMpTemplateData("UserName", user.getUserName()));
        templateMessage.addData(new WxMpTemplateData("UpperandlowerStatus", campusActivity.getUpperandlowerStatus()));
        templateMessage.addData(new WxMpTemplateData("publishId", campusActivity.getPublishId()));
        templateMessage.addData(new WxMpTemplateData("ActTypeName", campusActivity.getActTypeName()));
        templateMessage.addData(new WxMpTemplateData("ActLevelName", campusActivity.getActLevelName()));
        templateMessage.addData(new WxMpTemplateData("SportTypeName", campusActivity.getSportTypeName()));
        templateMessage.addData(new WxMpTemplateData("DepartmentsName", campusActivity.getDepartmentsName()));
        templateMessage.addData(new WxMpTemplateData("Name", campusActivity.getName()));
        templateMessage.addData(new WxMpTemplateData("StartTime", campusActivity.getStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("EndTime", campusActivity.getEndTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ApplyStartTime", campusActivity.getActivityApplyStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ApplyEndTime", campusActivity.getActivityApplyStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ActivityPlaceDetail", campusActivity.getActivityPlaceDetail().toString()));

        return templateMessage;
    }


    private WxMpTemplateMessage templateVip(Vip vip, CampusActivity campusActivity) throws IOException {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().build();
        templateMessage.setUrl(pushConfigure.getCAMPUSACTIVITYPAGEURL().replace("PUBLISH_ID", campusActivity.getPublishId()));
        templateMessage.setToUser(vip.getUserId());
        //推送课程id
        templateMessage.setTemplateId(pushConfigure.getViptemplateId());
        templateMessage.addData(new WxMpTemplateData("UserName", vip.getUserName()));
        templateMessage.addData(new WxMpTemplateData("UpperandlowerStatus", campusActivity.getUpperandlowerStatus()));
        templateMessage.addData(new WxMpTemplateData("publishId", campusActivity.getPublishId()));
        templateMessage.addData(new WxMpTemplateData("ActTypeName", campusActivity.getActTypeName()));
        //计算此类型的差值,通过api获取此类型的差值
        String difference = getDifference(vip.getXIdToken(), campusActivity.getSportTypeName());
        templateMessage.addData(new WxMpTemplateData("ActTypeScore", difference));
        templateMessage.addData(new WxMpTemplateData("ActLevelName", campusActivity.getActLevelName()));
        templateMessage.addData(new WxMpTemplateData("SportTypeName", campusActivity.getSportTypeName()));
        templateMessage.addData(new WxMpTemplateData("DepartmentsName", campusActivity.getDepartmentsName()));
        templateMessage.addData(new WxMpTemplateData("Name", campusActivity.getName()));
        templateMessage.addData(new WxMpTemplateData("StartTime", campusActivity.getStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("EndTime", campusActivity.getEndTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ApplyStartTime", campusActivity.getActivityApplyStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ApplyEndTime", campusActivity.getActivityApplyStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ActivityPlaceDetail", campusActivity.getActivityPlaceDetail().toString()));
        return templateMessage;
    }


    private WxMpTemplateMessage autoTemplate(CampusActivity campusActivity, Vip vip) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().build();
        templateMessage.setUrl(pushConfigure.getCAMPUSACTIVITYPAGEURL().replace("PUBLISH_ID", campusActivity.getPublishId()));
        templateMessage.setToUser(vip.getUserId());
        templateMessage.setTemplateId(pushConfigure.getAutoTemplateId());
        //推送课程id
        templateMessage.addData(new WxMpTemplateData("UserName", vip.getUserName()));
        templateMessage.addData(new WxMpTemplateData("publishId", campusActivity.getPublishId()));
        templateMessage.addData(new WxMpTemplateData("Name", campusActivity.getName()));
        templateMessage.addData(new WxMpTemplateData("StartTime", campusActivity.getStartTime().toString()));
        templateMessage.addData(new WxMpTemplateData("EndTime", campusActivity.getEndTime().toString()));
        templateMessage.addData(new WxMpTemplateData("ActivityPlaceDetail", campusActivity.getActivityPlaceDetail()));

        return templateMessage;
    }


    private WxMpTemplateMessage authorizationTemplate(User user) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().build();
        templateMessage.setUrl(pushConfigure.getWECHATAUTHURL() + "/wechat/authorize");
        templateMessage.setToUser(user.getUserId());
        //推送课程id
        templateMessage.setTemplateId(pushConfigure.getAuthorizationTemplateId());

        return templateMessage;
    }


    private WxMpTemplateMessage DeveloperTemplateMessage(User user, String developerName, String content) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().build();
        //推送公告
        templateMessage.setTemplateId(pushConfigure.getDeveloperTemplateId());
        templateMessage.setToUser(user.getUserId());
        templateMessage.addData(new WxMpTemplateData("UserName", user.getUserName()));
        templateMessage.addData(new WxMpTemplateData("DeveloperName", developerName));
        templateMessage.addData(new WxMpTemplateData("Content", content));


        return templateMessage;
    }

    @Override
    public String getDifference(String xToken, String educationType) {

        //请求url get
        int year = LocalDateTime.now().minusYears(1).getYear();
        //api通过时间获取,暂时这样规定,不知道学校api有什么尿性.
        //https://stuworkapp.sandau.edu.cn/api/supwisdom-stuwork-secendclass/v1/api/secondclass/actgrade/getMyActGradeTotal?schoolYear=2023

        String baseUrl = "https://stuworkapp.sandau.edu.cn/api/supwisdom-stuwork-secendclass/v1/api/secondclass/actgrade/getMyActGradeTotal?schoolYear=";
        String getVipScoreUrl = baseUrl + year;
        String jsonByVipScoreUrl = null;
        try {

            //根据educationType通过枚举类
            String educationCode = getByDescription(educationType);
            //生成min最小字段

            StringBuilder edcationTypeMinScoreBuilder = new StringBuilder(educationCode);
            edcationTypeMinScoreBuilder.append("MinScore");

            //生成grade当前分数字段
            StringBuilder edcationTypeNowGradeBuilder = new StringBuilder(educationCode);
            edcationTypeNowGradeBuilder.append("Grade");
            //获取当前分数的json数据
            jsonByVipScoreUrl = sendGetHearderRequest(getVipScoreUrl, xToken);
            JSONObject jsonObject = JSONObject.parseObject(jsonByVipScoreUrl);
            //取出嵌套的data字段
            JSONObject data = (JSONObject) jsonObject.get("data");
            Double MinScore = data.getDouble(edcationTypeMinScoreBuilder.toString());
            Double NowGrade = data.getDouble(edcationTypeNowGradeBuilder.toString());


            Double difference = MinScore - NowGrade;
            if (difference > 0) {
                return String.valueOf(difference);  // 如果差值大于 0，返回差值的字符串表示
            } else {
                return "0";  // 如果差值小于或等于 0，返回字符串 "0"
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
